package com.ly.service.impl;

import com.ly.mapper.StudentsMapper;
import com.ly.mapper.TClassMapper;
import com.ly.mapper.TStudentClassMapper;
import com.ly.mapper.TeachersMapper;
import com.ly.pojo.TStudentClass;
import com.ly.service.TStudentClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TStudentClassServiceImpl implements TStudentClassService {

    @Autowired
    private TStudentClassMapper tStudentClassMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private TClassMapper tClassMapper;


    @Override
    public Long insertStudentClassBySnoList(String classCode, String className, List<Long> selectedSnoList) {
        int count = 0;
        for (Long sno : selectedSnoList) {
            TStudentClass tStudentClass = new TStudentClass();
            tStudentClass.setClassCode(classCode);
            tStudentClass.setClassName(className);
            tStudentClass.setStudentSno(sno);
            tStudentClass.setStudentName(studentsMapper.selectNameBySno(sno));

            int i = tStudentClassMapper.insert(tStudentClass);
            if (i != 1) {
                return sno;
            }
            count++;
        }

        // 去更新对应班级的班级人数
        tClassMapper.updateCountByClassCode(classCode, count);

        return 1L;
    }

    @Override
    public Long deleteBySnoList(List<Long> selectedSnoList, String classCode) {
        int count = 0;
        for (Long sno : selectedSnoList) {
            int i = tStudentClassMapper.deleteBySno(sno);
            if (i != 1) {
                return sno;
            }
            count++;
        }

        // 删除学生班级信息的时候需要更新对应班级的人数
        tClassMapper.updateSubCountByClassCode(classCode, count);

        return 1L;
    }

    @Override
    public int deleteBySno(Integer id) {
        Long sno = studentsMapper.selectSnoById(id);
        return tStudentClassMapper.deleteBySno(sno);
    }

    @Override
    public int deleteByClassId(Integer id) {
        String classCode = tClassMapper.selectClassCodeById(id);
        return tStudentClassMapper.deleteByClassCode(classCode);
    }

    @Override
    public TStudentClass selectBySno(Long account) {
        return tStudentClassMapper.selectBySno(account);
    }
}
